const puppeteer = require('puppeteer');
const screenImg = require('./screenImg.js');

module.exports = {
  giteePublish: async (conf) => {
    console.log('Start deploying gitee pages service,please wait a moment')
    let startTime = (new Date()).getTime();
    let index = 0
    let autoScreen = async () => {
      await screenImg(page, index, conf.outputimgpath)
      index++
    }
    // 获取浏览器
    const browser = await puppeteer.launch({
      defaultViewport: {
        width: 1920,
        height: 1080
      }
    })
    // 开启新页面
    const page = await browser.newPage()
    // 监听alert
    page.on('dialog', async dialog => {
      if (dialog.message() === '确定重新部署 Gitee Pages 吗?') {
        await dialog.accept('确定重新部署 Gitee Pages 吗?')
        await page.waitFor(3000)
        await autoScreen()
        await browser.close()
        console.log('Deploying gitee pages service succeed!!!')
        console.log('Total time spent：' + ((new Date()).getTime() - startTime) / 1000 + 's')
      }
    })

    try {
      // 打开指定页面
      await page.goto('https://gitee.com')
      await autoScreen()
      // 找到登录按钮，并点击
      const loginElementHandler = await page.$('.git-nav-user__login-item')
      await loginElementHandler.click()
      // await page.waitFor(5000)
      await page.waitFor(() => {
        return document.querySelector('#user_login') &&
          document.querySelector('#user_password') &&
          document.querySelector("input[value='登 录']")
      })
      await autoScreen()
      // 找到输入账号密码input执行输入，找到登录btn执行登录
      await page.type('#user_login', conf.account, {
        delay: 100
      })
      await page.waitFor(200)
      await page.type('#user_password', conf.password, {
        delay: 100
      })
      await page.waitFor(200)
      await autoScreen()
      const loginBtnElementHandler = await page.$("input[value='登 录']")
      await loginBtnElementHandler.click()
      // await page.waitFor(4000)
      await page.waitFor(() => document.querySelector('.dashboard-sidebar > .user > .items > :first-child'))
      await autoScreen()
      // 点击查看所有仓库
      const repostoryBtnElementHandler = await page.$('.dashboard-sidebar > .user > .items > :first-child')
      await repostoryBtnElementHandler.click()
      // await page.waitFor(4000)
      await page.waitFor(() => document.querySelector('#search-projects'))
      await autoScreen()
      // 输入关键字，并进行搜索
      await page.type('#search-projects', conf.repository, {
        delay: 100
      })
      await page.waitFor(200)
      await page.keyboard.down('Enter')
      await page.waitFor(() => document.querySelector('#search-projects-ulist'))
      await page.waitFor(2000)
      await autoScreen()

      // 查询是否存在结果，存在进行点击,对结果进行完全匹配，如果是完全匹配，则进行点击
      const repositoryListElementHandler = await page.$$('#search-projects-ulist > *')
      if (repositoryListElementHandler.length > 0) {
        // 查看具体的仓库名称，看看是否存在匹配的情况
        let repositoryNameBtn = null
        let index = 0
        if (repositoryListElementHandler.length === 1) {
          let notDataFLag = await repositoryListElementHandler[0].$('.blank-message-notice')
          if (notDataFLag) {
            console.error(`[error] repository [${conf.repository}] is not find, please input a right name`)
            return await browser.close()
          }
        }
        for (let repositoryItem of repositoryListElementHandler) {
          let repositoryNameInfo = await repositoryItem.$('h4 > span > span > span')
          const repositoryName = await repositoryNameInfo.$eval('a', node => node.innerText.split('/')[1])
          if (repositoryName === conf.repository) {
            repositoryNameBtn = await repositoryNameInfo.$('a')
            break
          }
          index++
        }
        if (!repositoryNameBtn) {
          console.log(`repository [${conf.repository}] is not find, please input a right name`)
          await browser.close()
        } else {
          // 不直接点击，而是获取到a标签的href并重新new一个page来进行响应
          const result = await page.evaluate(index => {
            const repositoryDom = document.querySelector(`#search-projects-ulist > :nth-child(${index + 1}) > h4 > span > span > span > a`)
            if (repositoryDom) {
              repositoryDom.target = '_self'
              return repositoryDom
            } else {
              return null
            }
          }, index)
          await repositoryNameBtn.click()
          await page.waitFor(() => document.querySelector('.git-project-service'))
          await page.waitFor(500)
          await autoScreen()

          // 找到pages服务按钮，点击进入，并点击发布
          const gitService = await page.$('.git-project-service')
          await gitService.click()
          await page.waitFor(500)
          const pageServiceBtn = await page.$("div[class='menu transition visible'] > :first-child")
          await pageServiceBtn.click()
          await page.waitFor(() => document.querySelector('.redeploy-button'))
          const redeployBtn = await page.$('.redeploy-button')
          await redeployBtn.click()
        }
      } else {
        console.error(`[error] repository [${conf.repository}] is not find, please input a right name`)
        await browser.close()
      }
    } catch (err) {
      await browser.close()
      console.error(err)
    }
  }
}
